package com.tbit.main.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tbit.Version;
import com.tbit.main.constant.MachineStateConstant;
import com.tbit.main.constant.UqbikeManagerConfig;
import com.tbit.main.dao.capital.RideLogDetailsDao;
import com.tbit.main.dao.core.AccountDao;
import com.tbit.main.exception.BaseException;
import com.tbit.main.pojo.*;
import com.tbit.main.service.*;
import com.tbit.main.util.DateTimeUtil;
import com.tbit.main.util.GeoUtil;
import com.tbit.main.util.MD5PasswordUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author LMY
 * @create 2020-11-27 11:37
 * 运营简报2.0
 */
@Service("operationBriefingService")
@Slf4j
public class OperationBriefingServiceImpl implements OperationBriefingService {
    /**
     * 金额格式化
     */
    private DecimalFormat df = new DecimalFormat("0.00");
    @Autowired
    private UserService userService;
    @Autowired
    private MachineService machineService;
    @Autowired
    private RideCardService rideCardService;
    @Autowired
    private RideLogService rideLogService;
    @Autowired
    private MemberLogService memberLogService;
    @Autowired
    private DispatchLogService dispatchLogService;
    @Autowired
    private VipLogService vipLogService;
    @Autowired
    private RefundopeLogService refundopeLogService;
    @Autowired
    private AccountConfigService accountConfigService;
    @Autowired
    private MachineAbnormalService machineAbnormalService;
    @Autowired
    private GeoService geoService;
    @Autowired
    private MachineStatusService machineStatusService;
    @Autowired
    private MoveDayStaService moveDayStaService;
    @Autowired
    private PowerDayStaService powerDayStaService;
    @Autowired
    private DispatchDayStaService dispatchDayStaService;
    @Autowired
    private NewUserDayStaService newUserDayStaService;
    @Autowired
    private RideOrderDayStaService rideOrderDayStaService;
    @Autowired
    private RideCardOrderDayStaService rideCardOrderDayStaService;
    @Autowired
    private DepositOrderDayStaService depositOrderDayStaService;
    @Autowired
    private VipCardOrderDayStaService vipCardOrderDayStaService;
    @Autowired
    private PowerChangeLogService powerChangeLogService;
    @Autowired
    private MoveLogService moveLogService;
    @Autowired
    private AccountDataDayStaService accountDataDayStaService;
    @Autowired
    private UserMealLogService userMealLogService;
    @Autowired
    private UserRefundLogService userRefundLogService;
    @Autowired
    private RideRefundLogService rideRefundLogService;
    @Autowired
    private RideLogDetailsDao rideLogDetailsDao;
    @Resource
    private AccountDao accountDao;

    @Override
    public AgentSta getOrder(Integer accountId, String startTime, String endTime) {
        AgentSta agentSta = new AgentSta();
        agentSta.setAccountId(accountId);

        /**免押会员总数*/
        Integer memberUserCount = userService.getDepositUserCount(accountId, DateTimeUtil.getNowTimeYMD());
        agentSta.setMemberUserCount(memberUserCount);

        /**调度订单和费用*/
//        DispatchPaySta dispatchPaySta = dispatchLogService.staByTime(accountId, startTime, endTime);
        List<Integer> accountIds = new ArrayList<>();
        accountIds.add(accountId);
        if (-1 == accountId){
            throw new BaseException("未知区域不存在，请选择其他区域");
        }
        DispatchPaySta dispatchPaySta = getFoneMonney(accountDao.getByAccount(accountId), accountIds, startTime, endTime);
        agentSta.setDispatchCount(dispatchPaySta.getDispatchCount());
        if (dispatchPaySta.getDispatchMoney() == null) {
            agentSta.setDispatchMoney("0");
        } else {
            agentSta.setDispatchMoney(df.format(dispatchPaySta.getDispatchMoney() / 100));
        }

        /**骑行订单信息*/
        Map<String, Object> orderCumStaMap = rideOrderDayStaService.getByAccountId(accountId, startTime, endTime);
        if (orderCumStaMap != null) {
            agentSta.setOrderCount(Integer.parseInt(orderCumStaMap.get("orderCount").toString()));
            agentSta.setOrderMoney(df.format(Double.parseDouble(orderCumStaMap.get("orderMoney").toString()) / 100));
        } else {
            agentSta.setOrderCount(0);
            agentSta.setOrderMoney("0.00");
        }

        /**免押会员信息*/
        Map<String, Object> orderCumStaMemberStaMap = depositOrderDayStaService.getByAccountId(accountId, startTime, endTime);
        if (orderCumStaMemberStaMap != null) {
            agentSta.setMemberOrderCount(Integer.parseInt(orderCumStaMemberStaMap.get("orderCount").toString()));
            agentSta.setMemberOrderMoney(df.format(Float.parseFloat(orderCumStaMemberStaMap.get("orderMoney").toString()) / 100));
        } else {
            agentSta.setMemberOrderCount(0);
            agentSta.setMemberOrderMoney("0.00");
        }

        /**骑行会员信息*/
        Map<String, Object> orderCarCumStaMemberStaMap = rideCardOrderDayStaService.getByAccountId(accountId, startTime, endTime);
        if (orderCarCumStaMemberStaMap != null) {
            agentSta.setRideCardOrderCount(Integer.parseInt(orderCarCumStaMemberStaMap.get("orderCount").toString()));
            agentSta.setRideCardOrderMoney(df.format(Float.parseFloat(orderCarCumStaMemberStaMap.get("orderMoney").toString()) / 100));
        } else {
            agentSta.setRideCardOrderCount(0);
            agentSta.setRideCardOrderMoney("0.00");
        }

        /**会员卡会员信息*/
        Map<String, Object> orderCumStaVipStaMap = vipCardOrderDayStaService.getByAccountId(accountId, startTime, endTime);
        if (orderCumStaVipStaMap != null) {
            agentSta.setVipOrderCount(Integer.parseInt(orderCumStaVipStaMap.get("orderCount").toString()));
            agentSta.setVipOrderMoney(df.format(Float.parseFloat(orderCumStaVipStaMap.get("orderMoney").toString()) / 100));
        } else {
            agentSta.setVipOrderCount(0);
            agentSta.setVipOrderMoney("0.00");
        }

        /**优惠券金额，退款金额 信息*/
        BrandDataDaySta brandDataDaySta = accountDataDayStaService.getByAccountITimeMoney(accountId, startTime, endTime);
        if (brandDataDaySta != null) {
            agentSta.setCouponOrderMoney(brandDataDaySta.getCouponOrder());
            agentSta.setRefundMoney(brandDataDaySta.getRideCardRefund().add(brandDataDaySta.getVipCardRefund()).
                    add(brandDataDaySta.getDepositCardRefund()).add(brandDataDaySta.getCouponOrderRefund()).add(
                    brandDataDaySta.getRideOrderRefund()));
        } else {
            agentSta.setCouponOrderMoney(new BigDecimal(0));
            agentSta.setRefundMoney(new BigDecimal(0));
        }

        /**优惠券数量 信息*/
        BrandDataDaySta brandDataDayStaCount = accountDataDayStaService.getByAccountITimeCount(accountId, startTime, endTime);
        if (brandDataDayStaCount != null) {
            agentSta.setCouponOrderCount(brandDataDayStaCount.getCouponOrderCount());
        } else {
            agentSta.setCouponOrderCount(0);
        }

        if (endTime.substring(0, 10).equals(DateTimeUtil.getNowTimeYMD())) {


            /**骑行订单信息 当天
             * */
            RideSta rideStaOrderCumSta = rideLogService.staByTime(accountId, DateTimeUtil.getNowDateTimeBefore(0) + " 00:00:00", DateTimeUtil.getNowTime());
            if (rideStaOrderCumSta.getOrderCount() == null) {
                rideStaOrderCumSta.setOrderCount(0);
            }
            if (rideStaOrderCumSta.getOrderMoney() == null) {
                rideStaOrderCumSta.setOrderMoney(0.00);
            } else {
                rideStaOrderCumSta.setOrderMoney((double) rideStaOrderCumSta.getOrderMoney() / 100);
            }
            agentSta.setOrderCount(agentSta.getOrderCount() + rideStaOrderCumSta.getOrderCount());
            agentSta.setOrderMoney(df.format((Double.parseDouble(agentSta.getOrderMoney()) + rideStaOrderCumSta.getOrderMoney())));

            /**免押会员信息 当天
             * */
            MemberSta OrderCumSta = memberLogService.staByTimeByAccountId(accountId, DateTimeUtil.getNowDateTimeBefore(0) + " 00:00:00", DateTimeUtil.getNowTime());
            if (OrderCumSta.getMemberOrderCount() == null) {
                OrderCumSta.setMemberOrderCount(0);
            }
            if (OrderCumSta.getMemberOrderMoney() == null) {
                OrderCumSta.setMemberOrderMoney(0.00);
            } else {
                OrderCumSta.setMemberOrderMoney((double) OrderCumSta.getMemberOrderMoney() / 100);
            }
            agentSta.setMemberOrderCount(agentSta.getMemberOrderCount() + OrderCumSta.getMemberOrderCount());
            agentSta.setMemberOrderMoney(df.format((Double.parseDouble(agentSta.getMemberOrderMoney()) + OrderCumSta.getMemberOrderMoney())));

            /**骑行会员卡会员信息 当天
             * */
            RideCardSta rideCardDao = rideCardService.staByTime(accountId, DateTimeUtil.getNowDateTimeBefore(0) + " 00:00:00", DateTimeUtil.getNowTime());
            if (rideCardDao.getRideCardOrderCount() == null) {
                rideCardDao.setRideCardOrderCount(0);
            }
            if (rideCardDao.getRideCardOrderMoney() == null) {
                rideCardDao.setRideCardOrderMoney(0.00);
            } else {
                rideCardDao.setRideCardOrderMoney((double) rideCardDao.getRideCardOrderMoney() / 100);
            }
            agentSta.setRideCardOrderCount(agentSta.getRideCardOrderCount() + rideCardDao.getRideCardOrderCount());
            agentSta.setRideCardOrderMoney(df.format((Double.parseDouble(agentSta.getRideCardOrderMoney()) + rideCardDao.getRideCardOrderMoney())));

            /**会员卡会员信息 当天
             * */
            VipSta vipSta = vipLogService.staByTime(accountId, DateTimeUtil.getNowDateTimeBefore(0) + " 00:00:00", DateTimeUtil.getNowTime());
            if (vipSta.getVipOrderCount() == null) {
                vipSta.setVipOrderCount(0);
            }
            if (vipSta.getVipOrderMoney() == null) {
                vipSta.setVipOrderMoney(0.00);
            } else {
                vipSta.setVipOrderMoney((double) vipSta.getVipOrderMoney() / 100);
            }
            agentSta.setVipOrderCount(agentSta.getVipOrderCount() + vipSta.getVipOrderCount());
            agentSta.setVipOrderMoney(df.format((Double.parseDouble(agentSta.getVipOrderMoney()) + vipSta.getVipOrderMoney())));

            /**优惠券信息 当天
             * */
            CouponOrderSta couponOrderSta = userMealLogService.staByTime(accountId, DateTimeUtil.getNowDateTimeBefore(0) + " 00:00:00", DateTimeUtil.getNowTime());
            if (couponOrderSta.getCouponOrderCount() == null) {
                couponOrderSta.setCouponOrderCount(0);
            }
            if (couponOrderSta.getCouponOrderMoney() == null) {
                couponOrderSta.setCouponOrderMoney(0L);
            }
            agentSta.setCouponOrderCount(agentSta.getCouponOrderCount() + couponOrderSta.getCouponOrderCount());
            agentSta.setCouponOrderMoney(couponOrderSta.getCouponOrderMoney().add(agentSta.getCouponOrderMoney()));

            /**退款信息 当天
             * */
            UserRefundOrderSta userRefundOrderSta = userRefundLogService.staByTime(accountId, DateTimeUtil.getNowDateTimeBefore(0) + " 00:00:00", DateTimeUtil.getNowTime());
            if (userRefundOrderSta.getUserRefundMoney() == null) {
                userRefundOrderSta.setUserRefundMoney(0L);
            }
            agentSta.setRefundMoney(userRefundOrderSta.getUserRefundMoney().add(agentSta.getRefundMoney()));

            /**骑行退款信息 当天
             * */
            RideRefundOrderSta rideRefundOrderSta = rideRefundLogService.staByTime(accountId, DateTimeUtil.getNowDateTimeBefore(0) + " 00:00:00", DateTimeUtil.getNowTime());
            if (rideRefundOrderSta.getRideRefundMoney() == null) {
                rideRefundOrderSta.setRideRefundMoney(0L);
            }
            agentSta.setRefundMoney(rideRefundOrderSta.getRideRefundMoney().add(agentSta.getRefundMoney()));


        }

        if ((0 <= DateTimeUtil.getNewHour() && DateTimeUtil.getNewHour() <= 4) &&
                DateTimeUtil.isAfterToday(DateTimeUtil.getDayAgoTime(1), startTime) &&
                DateTimeUtil.isBeforeToday(DateTimeUtil.getDayAgoTime(1), endTime)) {


            /**骑行订单信息 前天
             * */
            Map<String, Object> orderCumStaMapT = rideOrderDayStaService.getByAccountId(accountId,
                    DateTimeUtil.getNowDateTimeBefore(-1) + " 00:00:00", DateTimeUtil.getNowDateTimeBefore(-1) + " 23:59:59");
            if (orderCumStaMapT == null || Integer.parseInt(orderCumStaMapT.get("orderCount").toString()) == 0) {
                RideSta rideStaOrderCumSta = rideLogService.staByTime(accountId,
                        DateTimeUtil.getNowDateTimeBefore(-1) + " 00:00:00", DateTimeUtil.getNowDateTimeBefore(-1) + " 23:59:59");
                if (rideStaOrderCumSta.getOrderCount() == null) {
                    rideStaOrderCumSta.setOrderCount(0);
                }
                if (rideStaOrderCumSta.getOrderMoney() == null) {
                    rideStaOrderCumSta.setOrderMoney(0.00);
                } else {
                    rideStaOrderCumSta.setOrderMoney((double) rideStaOrderCumSta.getOrderMoney() / 100);
                }
                agentSta.setOrderCount(agentSta.getOrderCount() + rideStaOrderCumSta.getOrderCount());
                agentSta.setOrderMoney(df.format((Double.parseDouble(agentSta.getOrderMoney()) + rideStaOrderCumSta.getOrderMoney())));
            }

            /**免押会员信息 前天
             * */
            Map<String, Object> orderCumStaMemberStaMapT = depositOrderDayStaService.getByAccountId(accountId, DateTimeUtil.getNowDateTimeBefore(-1) + " 00:00:00", DateTimeUtil.getNowDateTimeBefore(-1) + " 23:59:59");
            if (orderCumStaMemberStaMapT == null || Integer.parseInt(orderCumStaMemberStaMapT.get("orderCount").toString()) == 0) {
                MemberSta OrderCumSta = memberLogService.staByTimeByAccountId(accountId, DateTimeUtil.getNowDateTimeBefore(-1) + " 00:00:00", DateTimeUtil.getNowDateTimeBefore(-1) + " 23:59:59");
                if (OrderCumSta.getMemberOrderCount() == null) {
                    OrderCumSta.setMemberOrderCount(0);
                }
                if (OrderCumSta.getMemberOrderMoney() == null) {
                    OrderCumSta.setMemberOrderMoney(0.00);
                } else {
                    OrderCumSta.setMemberOrderMoney((double) OrderCumSta.getMemberOrderMoney() / 100);
                }
                agentSta.setMemberOrderCount(agentSta.getMemberOrderCount() + OrderCumSta.getMemberOrderCount());
                agentSta.setMemberOrderMoney(df.format((Double.parseDouble(agentSta.getMemberOrderMoney()) + OrderCumSta.getMemberOrderMoney())));
            }

            /**骑行会员卡会员信息 前天
             * */
            Map<String, Object> orderCarCumStaMemberStaMapT = rideCardOrderDayStaService.getByAccountId(accountId, DateTimeUtil.getNowDateTimeBefore(-1) + " 00:00:00", DateTimeUtil.getNowDateTimeBefore(-1) + " 23:59:59");
            if (orderCarCumStaMemberStaMapT == null || Integer.parseInt(orderCarCumStaMemberStaMapT.get("orderCount").toString()) == 0) {
                RideCardSta rideCardDao = rideCardService.staByTime(accountId, DateTimeUtil.getNowDateTimeBefore(-1) + " 00:00:00", DateTimeUtil.getNowDateTimeBefore(-1) + " 23:59:59");
                if (rideCardDao.getRideCardOrderCount() == null) {
                    rideCardDao.setRideCardOrderCount(0);
                }
                if (rideCardDao.getRideCardOrderMoney() == null) {
                    rideCardDao.setRideCardOrderMoney(0.00);
                } else {
                    rideCardDao.setRideCardOrderMoney((double) rideCardDao.getRideCardOrderMoney() / 100);
                }
                agentSta.setRideCardOrderCount(agentSta.getRideCardOrderCount() + rideCardDao.getRideCardOrderCount());
                agentSta.setRideCardOrderMoney(df.format((Double.parseDouble(agentSta.getRideCardOrderMoney()) + rideCardDao.getRideCardOrderMoney())));
            }

            /**会员卡会员信息 前天
             * */
            Map<String, Object> orderCumStaVipStaMapT = vipCardOrderDayStaService.getByAccountId(accountId, DateTimeUtil.getNowDateTimeBefore(-1) + " 00:00:00", DateTimeUtil.getNowDateTimeBefore(-1) + " 23:59:59");
            if (orderCumStaVipStaMapT == null || Integer.parseInt(orderCumStaVipStaMapT.get("orderCount").toString()) == 0) {
                VipSta vipSta = vipLogService.staByTime(accountId, DateTimeUtil.getNowDateTimeBefore(-1) + " 00:00:00", DateTimeUtil.getNowDateTimeBefore(-1) + " 23:59:59");
                if (vipSta.getVipOrderCount() == null) {
                    vipSta.setVipOrderCount(0);
                }
                if (vipSta.getVipOrderMoney() == null) {
                    vipSta.setVipOrderMoney(0.00);
                } else {
                    vipSta.setVipOrderMoney((double) vipSta.getVipOrderMoney() / 100);
                }
                agentSta.setVipOrderCount(agentSta.getVipOrderCount() + vipSta.getVipOrderCount());
                agentSta.setVipOrderMoney(df.format((Double.parseDouble(agentSta.getVipOrderMoney()) + vipSta.getVipOrderMoney())));
            }

            /**优惠券 前天
             * */
            BrandDataDaySta orderCumStaCouponStaMapT = accountDataDayStaService.getByAccountITimeMoney(accountId, DateTimeUtil.getNowDateTimeBefore(-1) + " 00:00:00", DateTimeUtil.getNowDateTimeBefore(-1) + " 23:59:59");
            if (orderCumStaCouponStaMapT == null || orderCumStaCouponStaMapT.getCouponOrder().equals(0)) {
                CouponOrderSta couponOrderSta = userMealLogService.staByTime(accountId, DateTimeUtil.getNowDateTimeBefore(-1) + " 00:00:00", DateTimeUtil.getNowDateTimeBefore(-1) + " 23:59:59");

                if (couponOrderSta.getCouponOrderCount() == null) {
                    couponOrderSta.setCouponOrderCount(0);
                }

                if (couponOrderSta.getCouponOrderMoney() == null) {
                    couponOrderSta.setCouponOrderMoney(0L);
                }
                agentSta.setCouponOrderCount(agentSta.getCouponOrderCount() + couponOrderSta.getCouponOrderCount());
                agentSta.setCouponOrderMoney(agentSta.getCouponOrderMoney().add(couponOrderSta.getCouponOrderMoney()));
            }

            /**退款 前天
             * */
            if (orderCumStaCouponStaMapT == null) {

                UserRefundOrderSta userRefundOrderSta = userRefundLogService.staByTime(accountId, DateTimeUtil.getNowDateTimeBefore(-1) + " 00:00:00", DateTimeUtil.getNowDateTimeBefore(-1) + " 23:59:59");
                if (userRefundOrderSta.getUserRefundMoney() == null) {
                    userRefundOrderSta.setUserRefundMoney(0L);
                }
                agentSta.setRefundMoney(agentSta.getRefundMoney().add(userRefundOrderSta.getUserRefundMoney()));
            } else {
                BigDecimal refundMoney = orderCumStaCouponStaMapT.getRideCardRefund().add(orderCumStaCouponStaMapT.getVipCardRefund()).
                        add(orderCumStaCouponStaMapT.getDepositCardRefund()).add(orderCumStaCouponStaMapT.getCouponOrderRefund());
                if (refundMoney.equals(0)) {
                    UserRefundOrderSta userRefundOrderSta = userRefundLogService.staByTime(accountId, DateTimeUtil.getNowDateTimeBefore(-1) + " 00:00:00", DateTimeUtil.getNowDateTimeBefore(-1) + " 23:59:59");
                    if (userRefundOrderSta.getUserRefundMoney() == null) {
                        userRefundOrderSta.setUserRefundMoney(0L);
                    }
                    agentSta.setRefundMoney(agentSta.getRefundMoney().add(userRefundOrderSta.getUserRefundMoney()));
                }
            }

            /**骑行退款信息 前天
             * */
            if (orderCumStaCouponStaMapT == null || orderCumStaCouponStaMapT.getRideOrderRefund().equals(0)) {
                RideRefundOrderSta rideRefundOrderSta = rideRefundLogService.staByTime(accountId, DateTimeUtil.getNowDateTimeBefore(-1) + " 00:00:00", DateTimeUtil.getNowDateTimeBefore(-1) + " 23:59:59");
                if (rideRefundOrderSta.getRideRefundMoney() == null) {
                    rideRefundOrderSta.setRideRefundMoney(0L);
                }
                agentSta.setRefundMoney(agentSta.getRefundMoney().add(rideRefundOrderSta.getRideRefundMoney()));
            }

        }
        /**退款总金额*/
        /*Integer refundMoney = refundopeLogService.getByAccountIdTime(accountId,startTime,endTime);
        if(refundMoney==null){
            agentSta.setRefundMoney("0");
        }else{
            agentSta.setRefundMoney(df.format((float)refundMoney/100));
        }*/


        /** 微信支付宝费率*/
        AccountConfig accountConfig = accountConfigService.getByAccountId(accountId);
        if (accountConfig != null) {
            if (accountConfig.getPayRate() == null) {
                agentSta.setPayRate(0);
            } else {
                agentSta.setPayRate(accountConfig.getPayRate());
            }
        }

        return agentSta;
    }

    /**
     * 调用管理端获取罚款
     * @param accountIds
     * @param startTime
     * @param endTime
     * @return
     */
    private DispatchPaySta getFoneMonney(Integer brandId, List<Integer> accountIds, String startTime, String endTime) {
        DispatchPaySta dispatchPaySta = new DispatchPaySta();

        if (Objects.isNull(startTime) || Objects.isNull(endTime)) {
            throw new BaseException("获取罚款开始时间或结束时间不允许为空");
        }
        if (CollectionUtil.isEmpty(accountIds)) {
            throw new BaseException("区域id不能为空");
        }
        String url = UqbikeManagerConfig.managersite + "/stat/getFineMoney.do";
        long date = System.currentTimeMillis();
        String param = "youqu";
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("accountIds", accountIds);
        requestBody.put("brandId", brandId);
        requestBody.put("startDt", startTime);
        requestBody.put("endDt", endTime);
        requestBody.put("date", date);
        requestBody.put("param", param);
        requestBody.put("sign", MD5PasswordUtil.MD5("TBIT" + date + param));
        String response = null;
        try {
            log.info("调用管理端获取罚款==={}", JSON.toJSONString(requestBody));
            response = HttpRequest.get(url)
                    .header("U-APP-VERSION", Version.VERSION)
                    .body(JSON.toJSONString(requestBody))
                    .execute().body();
            log.info("调用管理端结束,返回:{}", JSON.toJSONString(response));

            //返回数据转为map
            JSONObject jsonObject = JSON.parseObject(response);
            Map<String, Object> map = JSON.parseObject(JSON.toJSONString(jsonObject.get("data")), new TypeReference<Map<String, String>>() {
            });
            if (Objects.nonNull(map.get("c1")) || Objects.nonNull(map.get("c2"))) {
                dispatchPaySta.setDispatchCount(Integer.parseInt(map.get("c1").toString()));
                dispatchPaySta.setDispatchMoney(Double.parseDouble(map.get("c2").toString()));
            }
        } catch (Exception e) {
            log.error("获取罚款失败:{}", e);
            log.error("调用管理端获取罚款失败,入参:{},返回:{}", JSON.toJSONString(requestBody), JSON.toJSONString(response));
        }
        return dispatchPaySta;
    }

    @Override
    public AgentSta getOperation(Integer accountId, String startTime, String endTime) {
        AgentSta agentSta = new AgentSta();
        agentSta.setAccountId(accountId);

        /**用户总数*/
        Integer userCount = userService.getUserCount(accountId);
        if (userCount != null) {
            agentSta.setUserCount(userCount);
        } else {
            agentSta.setUserCount(0);
        }

        /**新增用户数*/
        Integer newUserCount = newUserDayStaService.getByAccountId(accountId, startTime, endTime);
        if (newUserCount == null) {
            agentSta.setNewUserCount(0);
        } else {
            agentSta.setNewUserCount(newUserCount);
        }

        if (endTime.substring(0, 10).equals(DateTimeUtil.getNowTimeYMD())) {
            /**新增用户数*/
            Integer newUserCountNew = userService.newUser(accountId, DateTimeUtil.getNowDateTimeBefore(0) + " 00:00:00", endTime);
            if (newUserCountNew == null) {
                agentSta.setNewUserCount(agentSta.getNewUserCount() + 0);
            } else {
                agentSta.setNewUserCount(agentSta.getNewUserCount() + newUserCountNew);
            }
        }

        if ((0 <= DateTimeUtil.getNewHour() && DateTimeUtil.getNewHour() <= 3) &&
                DateTimeUtil.isAfterToday(DateTimeUtil.getDayAgoTime(1), startTime) &&
                DateTimeUtil.isBeforeToday(DateTimeUtil.getDayAgoTime(1), endTime)) {
            Integer newUserCountT = newUserDayStaService.getByAccountId(accountId, DateTimeUtil.getNowDateTimeBefore(-1) + " 00:00:00", DateTimeUtil.getNowDateTimeBefore(-1) + " 23:59:59");
            if (newUserCountT == null || newUserCountT == 0) {
                Integer newUserCountNew = userService.newUser(accountId, DateTimeUtil.getNowDateTimeBefore(-1) + " 00:00:00", DateTimeUtil.getNowDateTimeBefore(-1) + " 23:59:59");
                if (newUserCountNew != null) {
                    agentSta.setNewUserCount(agentSta.getNewUserCount() + newUserCountNew);
                }
            }
        }


        /**投放车辆总数*/
        Integer machineCount = machineService.getCountByAccountId(accountId);
        if (machineCount == null) {
            agentSta.setMachineCount(0);
        } else {
            agentSta.setMachineCount(machineCount);
        }

        agentSta.setMachineUserCount(selectOperationalMachineCountByAccountIdOrRegionId(accountId,null));
        
        /**运营区域面积*/
        Geo geo = null;
        List<Geo> geos = geoService.getByAccountId(accountId);

        Integer accountIdArea = 0;
        if (!CollectionUtils.isEmpty(geos)) {
            geo = geos.get(0);
            List<Point> points = GeoUtil.getPoints(geo.getPoints());
            accountIdArea = GeoUtil.pointArea(points);
        }

        /**运营区域密度*/
        if (Objects.equals(0, accountIdArea)) {
            agentSta.setAccountIDensity((float) agentSta.getMachineCount() * 10000);
        } else {
            DecimalFormat df = new DecimalFormat("0.00");
            agentSta.setAccountIDensity(Float.parseFloat(df.format((float) agentSta.getMachineCount()
                    / (accountIdArea / 10000))));
        }

        //运营区域面积 由于前端是除于1000000并保留两位，所以这里取万位以上的数据
        agentSta.setAccountIdArea((accountIdArea / 10000) * 10000);

        return agentSta;
    }

    @Autowired
    private GeoreMachineService georeMachineService;

    public Integer selectOperationalMachineCountByAccountIdOrRegionId(Integer accountId,Integer regionId) {
        if (Objects.isNull(accountId) && Objects.isNull(regionId)) {
            return 0;
        }
        if (Objects.nonNull(regionId)) {
            Set<Integer> lackPowerMachineNos = Optional.ofNullable(georeMachineService.getRegionIdPower(regionId, accountId))
                    .map(x -> x.stream().map(MachineStatus::getMachineId).collect(Collectors.toSet()))
                    .orElse(Collections.emptySet());
            //异常车辆
            Set<Integer> abnormalNos = Optional.ofNullable(georeMachineService.getRegionIdAbnormal(regionId))
                    .map(x -> x.stream().map(MachineAbnormal::getMachineId).collect(Collectors.toSet()))
                    .orElse(Collections.emptySet());
            Set<Integer> machineIdList = machineService.selectMachineListByRegionIdAndState(regionId, MachineStateConstant.MACHINE_STATE_ZCYY)
                    .stream()
                    .map(Machine::getMachineId)
                    .collect(Collectors.toSet());
            machineIdList.removeAll(lackPowerMachineNos);
            machineIdList.removeAll(abnormalNos);
            return machineIdList.size();
        }else {
            AccountConfig accountConfig = accountConfigService.getByAccountId(accountId);
            //可运营车辆数  正在运营的（排除故障）- 缺电（用户借车电量） - 异常
            //缺电车辆
            Set<Integer> lackPowerMachineNos = Optional.ofNullable(machineStatusService.getSocByAccountId(accountId, accountConfig.getBorrowSocLimit()))
                    .map(x -> x.stream().map(MachineStatus::getMachineId).collect(Collectors.toSet()))
                    .orElse(Collections.emptySet());
            //异常车辆
            Set<Integer> abnormalNos = Optional.ofNullable(machineAbnormalService.getByAccountId(accountId))
                    .map(x -> x.stream().map(MachineAbnormal::getMachineId).collect(Collectors.toSet()))
                    .orElse(Collections.emptySet());
            //可运营车辆
            Set<Integer> machineIdList = machineService.selectMachineListByAccountIdAndState(accountId, MachineStateConstant.MACHINE_STATE_ZCYY)
                    .stream()
                    .map(Machine::getMachineId)
                    .collect(Collectors.toSet());
            machineIdList.removeAll(lackPowerMachineNos);
            machineIdList.removeAll(abnormalNos);
            return machineIdList.size();
        }
    }


    @Override
    public AgentSta getOPS(Integer accountId, String startTime, String endTime) {
        AgentSta agentSta = new AgentSta();
        agentSta.setAccountId(accountId);

        /**换电总次数*/
        Integer powerChangeCount = powerDayStaService.getByAccountId(accountId, startTime, endTime);
        if (powerChangeCount == null) {
            agentSta.setPowerChangeCount(0);
        } else {
            agentSta.setPowerChangeCount(powerChangeCount);
        }

        /**调度总次数*/
        Integer dispatchLogCount = dispatchDayStaService.getByAccountId(accountId, startTime, endTime);
        if (dispatchLogCount == null) {
            agentSta.setDispatchCounts(0);
        } else {
            agentSta.setDispatchCounts(dispatchLogCount);
        }

        /**挪车总次数*/
        Integer moveLogCount = moveDayStaService.getByAccountId(accountId, startTime, endTime);
        if (moveLogCount == null) {
            agentSta.setMoveCount(0);
        } else {
            agentSta.setMoveCount(moveLogCount);
        }

        if (endTime.substring(0, 10).equals(DateTimeUtil.getNowTimeYMD())) {
            /**换电总次数*/
            Integer powerChangeCountNew = powerChangeLogService.getByAccountIdTime(accountId, DateTimeUtil.getNowDateTimeBefore(0) + " 00:00:00", endTime);
            if (powerChangeCountNew == null) {
                agentSta.setPowerChangeCount(agentSta.getPowerChangeCount() + 0);
            } else {
                agentSta.setPowerChangeCount(agentSta.getPowerChangeCount() + powerChangeCountNew);
            }


            /**调度总次数*/
            Integer dispatchLogCountNew = dispatchLogService.getByAccountIdTime(accountId, 1, DateTimeUtil.getNowDateTimeBefore(0) + " 00:00:00", endTime, 1);
            if (dispatchLogCountNew == null) {
                agentSta.setDispatchCounts(agentSta.getDispatchCounts() + 0);
            } else {
                agentSta.setDispatchCounts(agentSta.getDispatchCounts() + dispatchLogCountNew);
            }

            /**挪车总次数*/
            Integer moveLogCountNew = moveLogService.groupByAccountIdTime(accountId, true, DateTimeUtil.getNowDateTimeBefore(0) + " 00:00:00", endTime);
            if (moveLogCountNew == null) {
                agentSta.setMoveCount(agentSta.getMoveCount() + 0);
            } else {
                agentSta.setMoveCount(agentSta.getMoveCount() + moveLogCountNew);
            }

        }

        if ((0 <= DateTimeUtil.getNewHour() && DateTimeUtil.getNewHour() <= 3) &&
                DateTimeUtil.isAfterToday(DateTimeUtil.getDayAgoTime(1), startTime) &&
                DateTimeUtil.isBeforeToday(DateTimeUtil.getDayAgoTime(1), endTime)) {

            long a7 = System.currentTimeMillis();
            Integer powerChangeCountT = powerDayStaService.getByAccountId(accountId, DateTimeUtil.getNowDateTimeBefore(-1) + " 00:00:00", DateTimeUtil.getNowDateTimeBefore(-1) + " 23:59:59");
            if (powerChangeCountT == null || powerChangeCountT == 0) {
                /**换电总次数前天*/
                Integer powerChangeCountNew = powerChangeLogService.getByAccountIdTime(accountId, DateTimeUtil.getNowDateTimeBefore(-1) + " 00:00:00", DateTimeUtil.getNowDateTimeBefore(-1) + " 23:59:59");
                if (powerChangeCountNew != null) {
                    agentSta.setPowerChangeCount(agentSta.getPowerChangeCount() + powerChangeCountNew);
                }
            }

            /**调度总次数*/
            Integer dispatchLogCountT = dispatchDayStaService.getByAccountId(accountId, DateTimeUtil.getNowDateTimeBefore(-1) + " 00:00:00", DateTimeUtil.getNowDateTimeBefore(-1) + " 23:59:59");
            if (dispatchLogCountT == null || dispatchLogCountT == 0) {
                /**调度总次数前天*/
                Integer dispatchLogCountNew = dispatchLogService.getByAccountIdTime(accountId, 1, DateTimeUtil.getNowDateTimeBefore(-1) + " 00:00:00", DateTimeUtil.getNowDateTimeBefore(-1) + " 23:59:59", 1);
                if (dispatchLogCountNew != null) {
                    agentSta.setDispatchCounts(agentSta.getDispatchCounts() + dispatchLogCountNew);
                }
            }

            /**挪车总次数*/
            Integer moveLogCountT = moveDayStaService.getByAccountId(accountId, DateTimeUtil.getNowDateTimeBefore(-1) + " 00:00:00", DateTimeUtil.getNowDateTimeBefore(-1) + " 23:59:59");
            if (moveLogCountT == null || moveLogCountT == 0) {
                /**挪车总次数前天*/
                Integer moveLogCountNew = moveLogService.groupByAccountIdTime(accountId, true, DateTimeUtil.getNowDateTimeBefore(-1) + " 00:00:00", DateTimeUtil.getNowDateTimeBefore(-1) + " 23:59:59");
                if (moveLogCountNew != null) {
                    agentSta.setMoveCount(agentSta.getMoveCount() + moveLogCountNew);
                }
            }
        }

        return agentSta;
    }

    @Override
    public Integer getRideIncomeByRegionId(Integer regionId, String startTime, String endTime) {
        return rideLogDetailsDao.getRideIncomeByRegionId(regionId, startTime, endTime);
    }
}
